package com.mxchip.livestar.ui.contact

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.mxchip.livestar.CallActivityA
import com.mxchip.livestar.R
import com.mxchip.livestar.base.CallLogViewModel
import com.mxchip.livestar.base.ContactPOJO
import com.mxchip.livestar.base.ContactViewModel
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.ui.GridItemDecoration
import com.mxchip.livestar.ui.P2PSingleCall
import kotlinx.android.synthetic.main.fragment_address_book.*

class AddressBookFragment : Fragment(), TextWatcher {

    private val contactViewModel by viewModels<ContactViewModel>()
    private val callLogViewModel by viewModels<CallLogViewModel>()

    private val mAdapter: AddressBookAdapter by lazy {
        AddressBookAdapter(this::onItemClick)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragment_address_book, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        contact_search_key.addTextChangedListener(this)

        val gridLayoutManager = GridLayoutManager(context, 2)
        recycler_view.addItemDecoration(GridItemDecoration(Color.TRANSPARENT, 0, 0, Color.TRANSPARENT, 0))
        recycler_view.setLayoutManager(gridLayoutManager)

        recycler_view.adapter = mAdapter
        recycler_view.showEmpty()

        contactViewModel.contactFilterList.observe(viewLifecycleOwner, Observer { list ->
            mAdapter.data = list
            mAdapter.notifyDataSetChanged()
        })

        button_add.setOnClickListener {
            val action = AddressBookFragmentDirections.actionAddressBookFragmentToAddMemberFragment()
            view.findNavController().navigate(action)
        }
    }

    private fun onItemClick(view: View, bean: ContactPOJO) {
        val addressBookDialog = AddressBookDialog(requireContext())
        addressBookDialog.setBean(bean)
        addressBookDialog.setOnClickListener { dialog: DialogInterface, which: Int ->
            Log.e(TAG, "which: $which")
            when (which) {
                0 -> {
                    bean.contactNumber?.let { makeCall(it) }
                }
                1 -> {

                    editContact(bean.contactName, bean.contactNumber, bean.rawContactId)
                }
                2 -> {
                    bean.rawContactId?.let { deleteContact(it) }
                }
            }
            dialog.dismiss()
        }
        addressBookDialog.setOnDismissListener { dialog: DialogInterface -> (dialog as AddressBookDialog).setOnClickListener(null) }
        addressBookDialog.show()
    }

    private fun editContact(name: String?, number: String?, id: Long) {
        val action = AddressBookFragmentDirections.
                actionAddressBookFragmentToAddMemberFragment()

        action.id = id
        action.name = name
        action.number =  number

        findNavController().navigate(action)
    }

    private fun deleteContact(id: Long) {
        contactViewModel.deleteContactByRawContactId(id)
    }

    private fun makeCall(number: String) {
        if (activity != null && !RoomClientRepository.connected()) {
            toast("网络未连接，暂时无法呼叫")
            return
        }
        val callNumber: String = number
        callLogViewModel.createCallLog(callNumber,"2")

        // val strings = arrayOf(callNumber.trim())
        context?.let { CallActivityA.open(it, P2PSingleCall(callNumber.trim())) }
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        contactViewModel.searchWord(if (count > 0) s.toString() else null)
    }

    override fun afterTextChanged(s: Editable) { }

    companion object {
        private const val TAG = "AddressBookFragment"
    }
}